#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#ifndef M_PI_2
#define M_PI_2 3.14159265358979323846/2.0
#endif

#include "TestCallback2.h"
#include <qdebug.h>
#include "qgsrasterlayer.h"
#include <string>
using std::string;
#include "QgsSingleBandGrayRenderer.h"
#include <qstring.h>

#include "QgsPalettedRasterRenderer.h"
#include "alayerdatawriter.h"


void TestCallback2::onAddButton()
{
	//qDebug() << "test add layer ...";
	//if (_mapCanvas && _pluginData != nullptr ) {
	//	QgsRasterLayer* testLayer = new QgsRasterLayer("E:\\data\\MODIS\\MOD13C2\\ndvi_rgb_rendered.tif", "test", "testdp");
	//	QgsRasterDataProvider* provider = testLayer->dataProvider();
	//	
	//	QString qtem = QString::fromStdString(_pluginData->_pixelFuncTemplate);
	//	QString pixelFunc = qtem.replace("$1", QString::number(_pluginData->_slideValue));
	//	QgsSingleBandGrayRenderer* render = new QgsSingleBandGrayRenderer(provider, 1);
	//	testLayer->setRenderer(render);
	//	provider->setProviderProperty(0, QVariant(pixelFunc));
	//	QgsRasterRangeList rangeList;
	//	rangeList.append(QgsRasterRange(0,0));
	//	provider->setUserNoDataValue(1, rangeList);
	//	QList<QgsMapLayer*> layers = _mapCanvas->layers();
	//	layers.append(testLayer);
	//	_mapCanvas->setLayers(layers);
	//	qDebug() << "add end";
	//}
}

void TestCallback2::onClearButton()
{
	qDebug() << "clear ...";
	if (_mapCanvas) {
		QList<QgsMapLayer*> empty;
		_mapCanvas->setLayers(empty);
		qDebug() << "clear end";
	}
	if (_pluginData) {
		delete _pluginData;
		_pluginData = nullptr;
	}
	if (_digitizeTool) {
		_digitizeTool->deleteLater();
		_digitizeTool = 0;
	}
	if (_memVecLayer) {
		_memVecLayer->deleteLater();
		_memVecLayer = 0;
	}
}

void TestCallback2::onSlider(int val)
{
	qDebug() << "sliding ...";
	if (_pluginData && _pluginData->isInited() ) {
		const static string scriptTemplate = R"(
			function forEachPixel(valArr) {
				if( valArr[0]>$1 ) return 1;
				else return 0;	
			}
		)";
		QString qtem = QString::fromStdString(scriptTemplate);
		QString pixelFunc = qtem.replace("$1", QString::number(val));
		_pluginData->updateForEachPixelFunc(pixelFunc.toStdString());
	}
}

void TestCallback2::onDrawROI()
{
	if (_pluginData == nullptr || _pluginData->isInited() == false) return;//skip
	if (_memVecLayer == 0) {
		QgsFields fields;
		QgsCoordinateReferenceSystem crs = QgsCoordinateReferenceSystem::fromEpsgId(4326);
		_memVecLayer = QgsMemoryProviderUtils::createMemoryLayer("scratch", fields, Qgis::WkbType::Polygon, crs);
		if (_memVecLayer == nullptr) {
			qDebug() << "debug bad QgsMemoryProviderUtils::createMemoryLayer ";
			return;
		}
		QList<QgsMapLayer*> layers = _mapCanvas->layers();
		layers.append(_memVecLayer);
		_mapCanvas->setLayers(layers);
	}
	if ( _digitizeTool == 0) {
		_adWidget = new QgsAdvancedDigitizingDockWidget(_mapCanvas);
		_digitizeTool = new QgsMapToolDigitizeFeature(_mapCanvas, _adWidget, QgsMapToolCapture::CapturePolygon);
		_digitizeTool->setCurrentCaptureTechnique(Qgis::CaptureTechnique::Streaming);

		_digitizeTool->connect(_digitizeTool, &QgsMapToolDigitizeFeature::digitizingCanceled, this, &TestCallback2::onDigitizingCanceled);
		_digitizeTool->connect(_digitizeTool, &QgsMapToolDigitizeFeature::digitizingCompleted, this, &TestCallback2::onDigitizingCompleted);
		_digitizeTool->connect(_digitizeTool, &QgsMapToolDigitizeFeature::digitizingFinished, this, &TestCallback2::onDdigitizingFinished);

		bool loadRes = false;
		_memVecLayer->loadSldStyle("E:/TempAndClean/vec-red-outline.sld", loadRes);
	}
	_mapCanvas->setCurrentLayer(_memVecLayer);
	_memVecLayer->startEditing();
	_mapCanvas->setMapTool(_digitizeTool);
}

TestCallback2::~TestCallback2()
{
	if (_pluginData) {
		delete _pluginData;
		_pluginData = 0;
	}
	if (_memVecLayer) _memVecLayer->deleteLater();
	_memVecLayer = 0;
	if(_adWidget) delete _adWidget;
	_adWidget = 0;
	if(_digitizeTool) delete _digitizeTool;
	_digitizeTool = 0;

}

void TestCallback2::onDigitizingCanceled()
{
	_mapCanvas->unsetMapTool(_digitizeTool);
}
void TestCallback2::onDigitizingCompleted(const QgsFeature& feature)
{
	_mapCanvas->unsetMapTool(_digitizeTool);
	QgsFeature newFeature = feature;
	_memVecLayer->commitChanges();
	if (_pluginData && _pluginData->isInited()) {
		_pluginData->useMask(newFeature);
	}
}

void TestCallback2::onDelRoi()
{
	_memVecLayer->commitChanges();
	if (_pluginData && _pluginData->isInited() ) {
		_pluginData->removeMask();
	}
}
void TestCallback2::onDdigitizingFinished()
{
	_mapCanvas->unsetMapTool(_digitizeTool);
}

void TestCallback2::onSave() {
	ARSSLayerDataWriter writer;
	bool isOk = false;
	string error;
	if (_pluginData->isUseMask()) {
		writer.writeRaster("E:/TempAndClean/test-shuihua.tif", _pluginData->getV8Layer(), Qgis::DataType::Byte,
			_pluginData->getMaskLayer(), "E:/coding/QT-Projects/QtQGisBin/gdalwarp.exe", error);
	}
	else {
		writer.writeRaster("E:/TempAndClean/test-shuihua.tif", _pluginData->getV8Layer(), Qgis::DataType::Byte, nullptr,
			"E:/coding/QT-Projects/QtQGisBin/gdalwarp.exe", error);
	}
	
}

void TestCallback2::onUsePlugin()
{
	string inurl = "E:/data/MODIS/MOD13C2/sr/mod13c2_20210101_nir.tif;E:/data/MODIS/MOD13C2/sr/mod13c2_20210101_red.tif|1";
	string bgname = "E:/data/MODIS/MOD13C2/sr/mod13c2_20210101_nir.tif";
	if (_pluginData) delete _pluginData; _pluginData = 0;
	_pluginData = new PluginData();
	_pluginData->init(inurl, bgname,"");
	QList<QgsMapLayer*> layers;
	layers.append(_pluginData->rootGroupLayer() );
	_mapCanvas->setLayers(layers);


	_pluginData->setV8LayerStyleQml("E:/TempAndClean/1style.qml");
	_pluginData->setOutlineLayerSldStyle("E:/TempAndClean/vec-red-outline.sld");
	_pluginData->setMaskLayerSldStyle("E:/TempAndClean/vec-style.sld");
}
